package vtc;

import java.util.*;

public class VtcFSM 
{
	String initialState_;
	String currentState_; 
	HashMap<String, HashMap<String, String>> fsm_;
	
	VtcFSM(String initialState)
	{
		initialState_ = initialState;
		currentState_ = initialState_;
		fsm_ = new HashMap<String, HashMap<String, String>>();
		fsm_.put(initialState, new HashMap<String, String>());
	}
	
	public String getCurrentState()
	{
		return currentState_;
	}
	
	public void AddState(String state)
	{
		fsm_.put(state, new HashMap<String, String>());
	}
	public void addTransition(String origin, String event, String target) throws VtcFSMException
	{
		if(fsm_.containsKey(origin))
		{
			fsm_.get(origin).put(event, target);
		}
		else
		{
			throw(new VtcFSMException("Error adding tarnsition: Origin state does not exist."));
		}
	}
	
	public void reset()
	{
		currentState_ = initialState_;
	}
	
	public boolean existTransition(String origin, String event)
	{
		if(fsm_.containsKey(origin))
		{
			if(fsm_.get(origin).containsKey(event))
				{
					return true;
				}
		}
		return false;
	}
	
	public void apply(String event)  throws VtcFSMException
	{
		if(fsm_.containsKey(currentState_))
		{
			if(fsm_.get(currentState_).containsKey(event))
			{
				currentState_ = fsm_.get(currentState_).get(event);
			}
		}
		else
		{
			throw(new VtcFSMException("Error applying event to fsm: current state " + currentState_ + " has not a transition named " + event + "."));
		}
	}
}
